//
//  Weather.m
//  Charles
//
//  Created by Leo on 2017/6/14.
//  Copyright © 2017年 charles. All rights reserved.
//

#import "Weather.h"

@interface WeatherData ()

@property (strong,nonatomic) NSMutableArray *observers;
@property (assign,nonatomic) CGFloat temperature;
@property (assign,nonatomic) CGFloat humidity;
@property (assign,nonatomic) CGFloat pressure;

@end

@implementation WeatherData

- (instancetype)init {
    if (self = [super init]) {
        self.observers = [[NSMutableArray alloc]initWithCapacity:0];
    }
    return self;
}

- (void)registerObserver:(id<Observer>)observer {
    if (![self.observers containsObject:observer]) {
        [self.observers addObject:observer];
    }
}

- (void)removeObserver:(id<Observer>)observer {
    NSInteger index = [self.observers indexOfObject:observer];
    if (index >= 0) {
        [self.observers removeObjectAtIndex:index];
    }
}

- (void)notifyObserver {
    for (int i = 0; i<self.observers.count; i++) {
        id<Observer> observer = self.observers[i];
        [observer updateTemp:self.temperature humidity:self.humidity pressure:self.pressure];
    }
}

- (void)measurementsChanged {
    [self notifyObserver];
}

- (void)setMeasurementsTemp:(CGFloat)temp humidity:(CGFloat)humidity pressure:(CGFloat)pressure {
    self.temperature = temp;
    self.humidity = humidity;
    self.pressure = pressure;
    [self measurementsChanged];
}

@end

@interface CurrentConditionsDisplay ()

@property (assign, nonatomic) CGFloat temperature;
@property (assign, nonatomic) CGFloat humidity;
@property (strong, nonatomic) id<Subject>weatherData;

@end

@implementation CurrentConditionsDisplay

-(void)setWeatherData:(id<Subject>)weatherData {
    _weatherData = weatherData;
    [weatherData registerObserver:self];
}

- (void)updateTemp:(CGFloat)temp humidity:(CGFloat)humidity pressure:(CGFloat)pressure {
    self.temperature = temp;
    self.humidity = humidity;
    [self display];
}

- (void)display {
    NSLog(@"%@",[NSString stringWithFormat:@"Current conditions: %f F degrees and %f humidity",self.temperature,self.humidity]);
}

@end

